package com.study.flink.java.day06_exactly;

import com.study.flink.java.utils.FlinkUtils;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.api.java.tuple.Tuple3;
import org.apache.flink.api.java.utils.ParameterTool;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.util.Collector;

public class FlinkKafkaToRedis {

    public static void main(String[] args) throws Exception {

        //ParameterTool parameters = ParameterTool.fromArgs(args);
        // 指定配置文件路径，路径最好以参数的方式传进来
        //ParameterTool parameters = ParameterTool.fromPropertiesFile("src/main/resources/config.properties");
        ParameterTool parameters = ParameterTool.fromPropertiesFile(args[0]);
        //String groupId = parameters.get("group.id", "gid-test");
        //String topics = parameters.getRequired("topics");
        //System.out.println(groupId);
        //System.out.println(topics);

        DataStream<String> lines = FlinkUtils.createKafkaStream(parameters, SimpleStringSchema.class);

        SingleOutputStreamOperator<String> words = lines.flatMap(new FlatMapFunction<String, String>() {
            @Override
            public void flatMap(String line, Collector<String> out) throws Exception {
                // 切分 压平
                String[] words = line.split(" ");
                for (String word : words) {
                    out.collect(word);
                }
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> wordAndCount = words.map(new MapFunction<String, Tuple2<String, Integer>>() {
            @Override
            public Tuple2<String, Integer> map(String s) throws Exception {
                // (单词,次数)
                return Tuple2.of(s, 1);
            }
        });

        SingleOutputStreamOperator<Tuple2<String, Integer>> summed = wordAndCount.keyBy(0).sum(1);

        // 整理成Tuple3放到redis里面
        SingleOutputStreamOperator<Tuple3<String, String, String>> redisMap = summed.map(new MapFunction<Tuple2<String, Integer>, Tuple3<String, String, String>>() {
            @Override
            public Tuple3<String, String, String> map(Tuple2<String, Integer> tp2) throws Exception {
                // 自由组合
                return Tuple3.of("WORD_COUNT_12", tp2.f0, tp2.f1.toString());
            }
        });
        redisMap.print();
        // 自定义redis sink
        redisMap.addSink(new MyRedisSink());

        FlinkUtils.getEnv().execute("FlinkKafkaToRedis-java");

    }


}
